package com.example.demo.leetcode.top100;

import java.util.ArrayDeque;
import java.util.LinkedList;
import java.util.List;
import java.util.Queue;

/**
 * ******************************************************
 *
 * @author liugh9
 * @version 1.0
 * @classname _45二叉树的右视图
 * @description
 * @date 2023/06/16 22:25
 * <p>
 * ******************************************************
 */
public class _45二叉树的右视图 {

    public List<Integer> rightSideView(TreeNode root) {
        List<Integer> result = new LinkedList<>();
        if (root == null) {
            return result;
        }
        LinkedList<TreeNode> q = new LinkedList<>();
        result.add(root.val);
        q.offer(root);
        while (!q.isEmpty()) {
            int size = q.size();
            for (int i = 0; i < size; i++) {
                TreeNode curr = q.poll();
                if (curr.left != null) {
                    q.offer(curr.left);
                }
                if (curr.right != null) {
                    q.offer(curr.right);
                }
            }
            if (!q.isEmpty()) {
                result.add(q.getLast().val);
            }
        }
        return result;
    }

    public static void main(String[] args) {
        _45二叉树的右视图 s = new _45二叉树的右视图();
        TreeNode a = new TreeNode(4);
        TreeNode b = new TreeNode(5);
        TreeNode c = new TreeNode(3, null, a);
        TreeNode d = new TreeNode(2, null, b);
        TreeNode e = new TreeNode(1, d, c);
        s.rightSideView(e);
    }

    public static class TreeNode {
        int val;
        TreeNode left;
        TreeNode right;

        TreeNode() {
        }

        TreeNode(int val) {
            this.val = val;
        }

        TreeNode(int val, TreeNode left, TreeNode right) {
            this.val = val;
            this.left = left;
            this.right = right;
        }
    }
}
